/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import i18n from 'i18next';

import {
  CommandDialog,
  DocumentEvents,
  DocumentObject,
  ICmdDialogParams,
  Icon,
  Types,
} from '@amcax/base';
import { CurvedBaseCommand } from '@app-cad/types';
import { useEffect, useState } from 'react';
import { wsApi } from '@app-cad/server';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { CommandFormWrapper } from '@app-base/common/components/command-form';
import { MouseActionInput } from '@app-base/common/components/pick-input/mouse-action-input';
import { userEvents } from '@app-base/module';
import { CommandFormFooter } from '@app-base/common/components/command-form/footer';

function ParameterSetCommand({ title, onClose }: ICmdDialogParams) {
  const [isLoading, setIsLoading] = useState(false);

  const [parent, setParent] = useState<DocumentObject>();

  const onSubmit = async () => {
    setIsLoading(true);
    try {
      await wsApi.createParameterSet(parent?.dxid);
    } finally {
      setIsLoading(false);
    }
    onClose();
  };

  const onObjectSelected = (selectedObject: DocumentObject) => {
    if (selectedObject.type === Types.PARAMETER_SET) {
      setParent(selectedObject);
    }
  };

  useEffect(() => {
    userEvents.on(DocumentEvents.SELECT_TREE_OBJECT, onObjectSelected);

    return () => {
      userEvents.off(DocumentEvents.SELECT_TREE_OBJECT, onObjectSelected);
    };
  }, []);

  useCommand('parameter-set', {
    onClose,
    finishDraw: onSubmit,
  });

  return (
    <CommandDialog
      onClose={onClose}
      title={title}
      placement='topLeft'>
      <CommandFormWrapper>
        <MouseActionInput
          active
          placeholder='请选择父数据集（可选）'>
          <div className='flex items-center'>
            {parent?.label}
            {parent != null && (
              <Icon
                className='ml-auto block'
                tabIndex={0}
                name='commons/close'
                onClick={() => {
                  setParent(null);
                }}
              />
            )}
          </div>
        </MouseActionInput>
        <CommandFormFooter
          isSubmitLoading={isLoading}
          onClose={onClose}
          onSubmit={onSubmit}
        />
      </CommandFormWrapper>
    </CommandDialog>
  );
}

export const cmdParameterSet: CurvedBaseCommand = {
  id: 'CmdParameterSet',
  label: '创建参数集',
  icon: 'commands/common/parameters-set',
  create: (label, onClose) => (
    <ParameterSetCommand
      title={i18n.t(label)}
      onClose={onClose}
    />
  ),
};
